package com.my.screenadapter.usb;

import android.annotation.SuppressLint;
import android.content.Context;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.util.Log;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

/**
 * Created by zhangyingjie on 2019-09-06
 *
 * @function
 */
public class UsbUtil {

    private static final String TAG = "UsbUtil";
    public static List<String> GetUsbPathNames(Context context) {
        List<String> usbNames = new ArrayList();
//        usbNames.add("/dev/bus/usb/001/039hello");
        @SuppressLint("WrongConstant")
        UsbManager usbManager = (UsbManager)context.getApplicationContext().getSystemService(Context.USB_SERVICE);
        HashMap<String, UsbDevice> usbList = usbManager.getDeviceList();
        Iterator deviceIterator = usbList.values().iterator();

            while(deviceIterator.hasNext()) {
                UsbDevice device = (UsbDevice)deviceIterator.next();

                Log.i(TAG, "GetUsbPathNames: " + (device!=null ? device.getDeviceName() :"null"));

                for(int iInterface = 0; iInterface < device.getInterfaceCount(); ++iInterface) {
                    if (device.getInterface(iInterface).getInterfaceClass() == 7 && device.getInterface(iInterface).getInterfaceSubclass() == 1 && CheckUsbVid(device)) {
                        usbNames.add(device.getDeviceName());
                        break;
                    }
                }
            }

            if (usbNames.size() == 0) {
                usbNames = null;
            }
            return usbNames;
    }

    private static boolean CheckUsbVid(UsbDevice usbDevice) {
        // TODO: Vender ID 和 Product ID, 即“厂家标识”和“产品标识”
        //USB 设备驱动的硬件接口需要识别 Vender ID 和 Product ID
        int[] xprinterUsbID = new int[]{1659, 1046, 7358, 1155, 8137, 1003, 11575, 1208, 22304, 26728};
        int vid = usbDevice.getVendorId();
        int[] var6 = xprinterUsbID;
        int var5 = xprinterUsbID.length;

        for(int var4 = 0; var4 < var5; ++var4) {
            int id = var6[var4];
            if (vid == id) {
                return true;
            }
        }

        return false;
    }
}
